//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState } from "react";
import { Form, Input, Modal } from "antd";
import { create as create_roadmap,update as update_roadmap } from "@/api/roadmap_admin";
import { get_admin_session } from "@/api/admin_auth";
import { request } from "@/utils/request";
import type { RoadmapInfo } from "@/api/roadmap";

export interface EditRoadmapModalProps {
    roadmap?: RoadmapInfo;
    onOk: () => void;
    onCancel: () => void;
}

const EditRoadmapModal = (props: EditRoadmapModalProps) => {
    const [title, setTitle] = useState(props.roadmap?.basic_info.title ?? "");
    const [desc, setDesc] = useState(props.roadmap?.basic_info.desc ?? "");

    const createRoadmap = async () => {
        const sessionId = await get_admin_session();
        await request(create_roadmap({
            session_id: sessionId,
            basic_info: {
                title: title,
                desc: desc,
            },
        }));
        props.onOk();
    };

    const updateRoadmap = async () => {
        if(props.roadmap == undefined){
            return;
        }
        const sessionId = await get_admin_session();
        await request(update_roadmap({
            session_id: sessionId,
            roadmap_id: props.roadmap.roadmap_id,
            basic_info: {
                title: title,
                desc: desc,
            },
        }));
        props.onOk();
    };

    return (
        <Modal open title="创建路线图" mask={false}
            okText={props.roadmap == undefined ? "创建" : "更新"} okButtonProps={{ disabled: title == "" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                if (props.roadmap == undefined) {
                    createRoadmap();
                }else {
                    updateRoadmap();
                }
            }}>
            <Form labelCol={{ span: 2 }}>
                <Form.Item label="标题">
                    <Input value={title} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setTitle(e.target.value.trim());
                    }} />
                </Form.Item>
                <Form.Item label="备注">
                    <Input.TextArea value={desc} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setDesc(e.target.value);
                    }} autoSize={{ minRows: 5, maxRows: 5 }} />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default EditRoadmapModal;